#include "hx710.h"
#include "data.h"

#define HX710_PORT               GPIOB
#define HX710_SCK                GPIO_PIN_8
#define HX710_OUT                GPIO_PIN_9
#define HX710_SCK_H()            HX710_PORT->BSRR = HX710_SCK
#define HX710_SCK_L()            HX710_PORT->BRR 	= HX710_SCK
#define HX710_OUT_H()            HX710_PORT->BSRR = HX710_OUT
#define HX710_OUT_L()            HX710_PORT->BRR 	= HX710_OUT
#define HX710_OUT_PIN()          HX710_PORT->IDR 	& HX710_OUT

//****************************************************
//初始化HX710
//****************************************************
void HX710_Init(void)
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};

	/* Enable SMBUS_PORT clocks */
	__HAL_RCC_GPIOB_CLK_ENABLE();

	/*Configure GPIO pins : PBPin PBPin PBPin */
	GPIO_InitStruct.Pin = HX710_SCK;
	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	HAL_GPIO_Init(HX710_PORT, &GPIO_InitStruct);
	
	GPIO_InitStruct.Pin = HX710_OUT;
	GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
	GPIO_InitStruct.Pull = GPIO_NOPULL;
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
	HAL_GPIO_Init(HX710_PORT, &GPIO_InitStruct);
	
	Get_Zero();
}

//****************************************************
//获取毛皮重量
//****************************************************
void Get_Zero(void)
{
  data_getData()->Weight_Zero = (int)HX710_Read()/100;   
} 

//****************************************************
//称重
//****************************************************
u16 Get_Pressure(void)
{
  data_getData()->Weight_Real = HX710_Read()/100;
  data_getData()->Weight_Stab = data_getData()->Weight_Real - data_getData()->Weight_Zero;       //获取实物的AD采样数值。
  if(data_getData()->Weight_Stab<0)
	{
		data_getData()->Weight_Zero += data_getData()->Weight_Stab;
		data_getData()->Weight_Stab = 0;
	}
  data_getData()->Weight_Pres = (unsigned int)((float)data_getData()->Weight_Stab/133.3);   
	//计算实物的实际重量
	//因为不同的传感器特性曲线不一样，因此，每一个传感器需要矫正这里的4.30这个除数。
	//当发现测试出来的重量偏大时，增加该数值。
	//如果测试出来的重量偏小时，减小改数值。
	//该数值一般在7.16左右。因传感器不同而定。
	//+0.05是为了四舍五入百分位

  return data_getData()->Weight_Pres;
}

//****************************************************
//读取HX710
//****************************************************
u32 HX710_Read(void)  //增益128
{
  u32 count; 
  u8 i;
	
  HX710_OUT_H();
  delay_us(1);
  HX710_SCK_L(); 
  delay_us(1);
	count=0; 
	while(HX710_OUT_PIN()); 
	for(i=0;i<24;i++)
  { 
		HX710_SCK_H();
		delay_us(1);
		count=count<<1; 
		HX710_SCK_L(); 
		delay_us(1);
		if(HX710_OUT_PIN())
		count++; 
  }
	HX710_SCK_H();
  count ^= 0x800000;
  delay_us(1);
  HX710_SCK_L();
  delay_us(1);
  
  return(count);
}
